<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Logic\Sms;
use App\Logic\Code;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Models\User;


class UserController extends Controller
{

    /**
     * @OA\Post(
     *     path="/admin/userIndex",
     *     tags={"后台用户"},
     *     summary="用户列表",
     *     @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"key","val"},
     *                 @OA\Property(property="key", type="string", description="搜索字段 id,username,phone,nick_name"),
     *                 @OA\Property(property="val", type="string", description="搜索值"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function index(Request $request)
    {
        $where = [];
        if($request->has('limit')){
            $limit = $request->input('limit');
        }else{
            $limit = 15;
        }
        $post_data = $request->all();
        if(isset($post_data['key']) && isset($post_data['val']) && $post_data['key'] != "" && $post_data['val'] != ""){
            $where[] = [$post_data['key'],'=',$post_data['val']];
        }
        $admin_list = Db::table('user')
                ->where($where)
                ->orderByDesc('id')
            ->paginate($limit);

        return s_msg('',$admin_list);
    }

    /**
     * @OA\Post(
     *     path="/admin/userXq",
     *     tags={"后台用户"},
     *     summary="用户详情",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"user_id"},
     *                 @OA\Property(property="user_id", type="number", description="管理员id"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function xq(Request $request)
    {
        if($request->has('user_id')){
            $user_info = Db::table('user')
                ->where('id',$request->input('user_id'))
                ->first();
            if($user_info){
                return s_msg('',$user_info);
            }else{
                return e_msg(300020,'用户信息不存在');
            }

        }else{
            return e_msg(300019,'未传入id');
        }

    }



    /**
     * @OA\Post(
     *     path="/admin/userReset",
     *     tags={"后台用户"},
     *     summary="重置密码",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 @OA\Property(property="id", type="number", description="用户id"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function reset(Request $request)
    {

        if($request->has('id')){
            $id = $request->input('id');
            $password = '123456';
            return User::reset($id,$password);

        }else{

            return e_msg(300019,'为传入用户id id');

        }

    }


    /**
     * @OA\Post(
     *     path="/admin/userPhone",
     *     tags={"后台用户"},
     *     summary="修改手机号",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 @OA\Property(property="id", type="number", description="用户id"),
     *                 @OA\Property(property="phone", type="string", description="用户手机号"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function phone(Request $request)
    {

        if($request->has('id')){
            $id = $request->input('id');
            $phone = $request->input('phone');

            if($phone){

                if(!preg_match("/^1[3456789]\d{9}$/",$phone)){
                    return e_msg(123456,'手机号不符合规则');
                }

                $already_id = DB::table('user')->where('phone',$phone)->value('id');
                if($already_id){
                    return e_msg(123456,'该手机号已存在');
                }
                return User::phone($id,$phone);
            }else{
                return e_msg(300019,'未传入用户手机号 phone');
            }
        }else{
            return e_msg(300019,'未传入用户id id');
        }

    }


    /**
     * @OA\Post(
     *     path="/admin/userDelete",
     *     tags={"后台用户"},
     *     summary="用户删除",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"user_id"},
     *                 @OA\Property(property="user_id", type="number", description="用户id"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function delete(Request $request)
    {

        if($request->has('user_id')){
            if($request->input('user_id') == 1) {
                return e_msg(300021,'第一个用户不能删除');
            }
            $user_info = Db::table('user')
                ->where('id',$request->input('user_id'))
                ->first();
            if($user_info){
                $down = DB::table('user')->where('pid',$request->input('user_id'))->get()->toArray();
                if(count($down) > 0 ){
                    return e_msg(300022,'该用户已推荐下级不能删除');
                }
                return e_msg(123,'删除功能暂不可用');
                $rel = DB::table('user')->where('id',$request->input('user_id'))->delete();
                return s_msg('');
            }else{
                return e_msg(300020,'用户信息不存在');
            }
        }else{
            return e_msg(300019,'未传入id');
        }

    }

    /**
     * @OA\Post(
     *     path="/admin/userLevel",
     *     tags={"后台用户"},
     *     summary="修改用户等级",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"id","level_lock","level"},
     *                 @OA\Property(property="id", type="number", description="用户id"),
     *                 @OA\Property(property="level", type="number", description="修改后的用户等级（范围在配置中获取）"),
     *                 @OA\Property(property="level_lock", type="number", description="锁定是1 不锁定是0"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function level(Request $request)
    {

        $post_data = $request->all();

        $validateRule = [
            'id' => 'required',
            'level' => 'required|numeric',
            'level_lock' => 'required|numeric',
        ];
        $errorMsg = [
            'id.required' => '请传入用户id id',
            'level.required' => '请传入level',
            'level.numeric' => '传入level非法',
            'level_lock.required' => '请传入level_lock',
            'level_lock.numeric' => '传入level_lock非法',
        ];

        $validator = Validator::make($post_data, $validateRule, $errorMsg);
        if ($validator->fails()) {
            $errors = $validator->errors()->all();
            return e_msg(300001, $errors[0]);
        }
        $update_arr = [
            'level' => $post_data['level'],
            'level_lock' => $post_data['level_lock'],
        ];
        $user_info = Db::table('user')
            ->where('id',$post_data['id'])
            ->update($update_arr);
        if($user_info){
            return s_msg('');
        }else{
            return e_msg(300020,'你没有作出修改');
        }
    }
    /**
     * @OA\Post(
     *     path="/admin/userState",
     *     tags={"后台用户"},
     *     summary="修改用户state",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"id","level_lock","level"},
     *                 @OA\Property(property="id", type="number", description="用户id"),
     *                 @OA\Property(property="state", type="number", description="修改后的用户state（范围1，2，3）"),
     *                 @OA\Property(property="state_lock", type="number", description="锁定 1 不锁定 0"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function state(Request $request)
    {

        $post_data = $request->all();

        $validateRule = [
            'id' => 'required',
            'state' => 'required|numeric',
            'state_lock' => 'required|numeric',
        ];
        $errorMsg = [
            'id.required' => '请传入用户id id',
            'state.required' => '请传入state',
            'state.numeric' => '传入state非法',
            'state_lock.required' => '请传入state_lock',
            'state_lock.numeric' => '传入state_lock非法',
        ];

        $validator = Validator::make($post_data, $validateRule, $errorMsg);
        if ($validator->fails()) {
            $errors = $validator->errors()->all();
            return e_msg(300001, $errors[0]);
        }
        $update_arr = [
            'state' => $post_data['state'],
            'state_lock' => $post_data['state_lock'],
        ];
        $user_info = Db::table('user')
            ->where('id',$post_data['id'])
            ->update($update_arr);
        if($user_info){
            return s_msg('');
        }else{
            return e_msg(300020,'你没有作出修改');
        }
    }
    
    
   /**
     * @OA\Post(
     *     path="/admin/userRegional",
     *     tags={"后台邀请"},
     *     summary="邀请信息",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"phone"},
     *                 @OA\Property(property="phone", type="string", description="用户phone"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function regional(Request $request)
    {
        $post_data = $request->all();

        $validateRule = [
            'phone' => 'required',
        ];
        $errorMsg = [
            'phone.required' => '请传入用户id id',
        ];

        $validator = Validator::make($post_data, $validateRule, $errorMsg);
        if ($validator->fails()) {
            $errors = $validator->errors()->all();
            return e_msg(300001, $errors[0]);
        }

        $u = DB::table('user')->where('phone', $post_data['phone'])->first();
        if (!$u) {
            return e_msg(123456, '该用户不存在');
        }
        $hspace = DB::table('miner_user')->where('user_name',$u->username)->select('mid')->get()->toArray();
        $arr = array_column($hspace,'mid');
        $u->capacity =  DB::table('miner_host')->whereIn('mid',$arr)->sum('hspace');
        
        //fil的值
        $whereFil[] =  ["mb.token" ,"=",'FIL'] ;
        $whereFil[] =  ["mu.user_name" ,"=", $u->username] ;
        $fil =  DB::table("miner_balance as mb")
            ->leftjoin("miner_user as mu" , "mu.mid","=","mb.mid")
            ->where($whereFil)
            ->sum("amount") ;
        $u->fil = number_format($fil , 4) ;

        //获取此人直推，，，直推分别的业绩   取大区 取小区
        $direct = DB::table('user')->where('pid', $u -> id )->get()->toArray();
        $childCount = count($direct) ;
        $u->childCount =  $childCount;
        if (!$direct) {
            $arr = [
                'user' => $u,
                'big_inviter_count' => 0,
                'small_inviter_count' => 0,
                'big_performance' => 0,
                'small_performance' => 0,
                'big_capacity' => 0,
                'small_capacity' => 0,
//                'big' => [],
//                'small' => [],
            ];
            return s_msg('', $arr);

        }

        $arr = array_column($direct, 'capacity');

        $max = max($arr);
        $key = array_keys($arr, $max)[0];
        $da = $direct[$key];
        unset($direct[$key]);
        $xiao[] = $direct;
        $big[] = $da;

        $all_count = DB::table('user')
            ->where('path', 'like', $u->path . $u->id . ',%')
            ->count();
        $da_count = DB::table('user')
                ->where('path', 'like', $da->path . $da->id . ',%')
                ->count() + 1;
        $xiao_count = $all_count - $da_count;

        $xiao_capacity_arr = array_column($direct, 'capacity');
        $xiao_capacity = array_sum($xiao_capacity_arr);

        $xiao_performance_arr = array_column($direct, 'performance');
        $xiao_performance = array_sum($xiao_performance_arr);

        $arr = [
            'user' => $u,
            'big_inviter_count' => $da_count,       //大区数量
            'small_inviter_count' => $xiao_count,      //小区数量
            'big_performance' => $da->performance,      //大区业绩
            'small_performance' => $xiao_performance,     //小区业绩
            'big_capacity' => $da->capacity,            //大区算力
            'small_capacity' => $xiao_capacity,         //小区算力
//            'big' => $big,
//            'small' => $xiao,
        ];

        return s_msg('', $arr);
    }

    /**
     * @OA\Post(
     *     path="/admin/userChild",
     *     tags={"后台邀请"},
     *     summary="下级用户",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"phone"},
     *                 @OA\Property(property="phone", type="string", description="用户手机"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function child(Request $request)
    {
        $post_data = $request->all();

        $validateRule = [
            'phone' => 'required',
        ];
        $errorMsg = [
            'phone.required' => '请传入用户手机号 phone',
        ];

        $validator = Validator::make($post_data, $validateRule, $errorMsg);
        if ($validator->fails()) {
            $errors = $validator->errors()->all();
            return e_msg(300001, $errors[0]);
        }

        $u = DB::table('user')->where('phone', $post_data['phone'])->first();
        if (!$u) {
            return e_msg(123456, '该用户不存在');
        }
        $direct = DB::table('user')->where('pid', $u->id)->orderByDesc('capacity')
            ->get()
            ->each(function($item){
                $hspace = DB::table('miner_user')->where('user_name',$item->username)->select('mid')->get()->toArray();
                $arr = array_column($hspace,'mid');
                $item->capacity =  DB::table('miner_host')->whereIn('mid',$arr)->sum('hspace');
            })
            ->toArray();
        return s_msg('', $direct);
    }

}
